package com.preserve.common.authentication.realm;

import java.io.Serializable;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.preserve.common.user.model.Users;
import com.preserve.common.user.service.IUsersService;
import com.preserve.core.utils.spring.SpringBeanUtil;

public class BaseShiroRealm extends AuthorizingRealm {

	private IUsersService service;

	private IUsersService getUserService() {
		if (service == null) {
			service = (IUsersService) (SpringBeanUtil.getBean("usersService"));
		}
		return service;
	}

	/**
	 * 权限验证--后面补充
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principal) {
		PreserveUser preserveUser = (PreserveUser) principal
				.getPrimaryPrincipal();
		String loginName = preserveUser.getLoginName();
		Users users = getUserService().getUserByName(loginName);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		if (users != null) {
			
		}
		return null;
	}

	/**
	 * 登陆验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

		// 通过表单接收的用户名
		String username = token.getUsername();
		if (username != null && !"".equals(username)) {
			Users users = getUserService().getUserByName(username);
			if (users != null) {
				return new SimpleAuthenticationInfo(new PreserveUser(
						users.getFdId(), users.getUserLogin(),
						users.getUserNicename()), users.getUserPwd(), getName());
			}
		}
		return null;
	}

	/**
	 * 封装登陆对象
	 */
	public static class PreserveUser implements Serializable {
		private static final long serialVersionUID = -3350074487024599768L;
		public Long id;
		public String loginName;
		public String nicename;

		public PreserveUser(Long id, String loginName, String nicename) {
			this.id = id;
			this.loginName = loginName;
			this.nicename = nicename;
		}

		public Long getId() {
			return this.id;
		}

		public String getLoginName() {
			return loginName;
		}

		public String getNicename() {
			return nicename;
		}
	}

}
